package net.app.help.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import net.app.help.R;
import net.app.help.adapters.EditGroupContactsListViewAdapter;
import net.app.help.adapters.GroupsListViewAdapter;
import net.app.help.db.DatabaseAdapter;
import net.app.help.dialogs.AttachMessageDialog;
import net.app.help.dialogs.EditGroupDialog;
import net.app.help.model.Contact;
import net.app.help.model.Group;
import net.app.help.model.Message;

import java.util.ArrayList;

public class GroupsActivity extends ActionBarActivity implements AttachMessageDialog.onConfirmInterface, EditGroupDialog.OnConfirmInterface {

	private DatabaseAdapter da = new DatabaseAdapter(this);
	private boolean[] selected;
	private Group g;								//selectedGroup
	private ArrayList<Contact> requiredContacts;
	private ArrayList<Message> messages;
	private ArrayList<Group> groups;
	private ArrayList<Contact> contacts;
	private Button addGroupButton, delGroupButton;
	private Button addContacts, remContacts;
	private Button attMessageButton, remMessageButton;
	private ListView groupsListView;
	private GroupsListViewAdapter groupsListViewAdapter;
	private Context context;

	private EditText name;

	private ListView editContactsListView;
	private EditGroupContactsListViewAdapter editGroupContactsListViewAdapter;

	public void setupViews() {
		addGroupButton = (Button) findViewById(R.id.act_gro_b_add_group);
		addGroupButton.setOnClickListener(addGroupListener);
		delGroupButton = (Button) findViewById(R.id.act_gro_b_delete_group);
		delGroupButton.setOnClickListener(deleteGroupListener);

		addContacts = (Button) findViewById(R.id.act_gro_b_add_contacts);
		addContacts.setOnClickListener(addContactsListener);
		remContacts = (Button) findViewById(R.id.act_gro_b_remove_contacts);
		remContacts.setOnClickListener(removeContactsListener);

		attMessageButton = (Button) findViewById(R.id.act_gro_b_attach_message);
		attMessageButton.setOnClickListener(attachMessageListener);
		remMessageButton = (Button) findViewById(R.id.act_gro_b_remove_message);
		remMessageButton.setOnClickListener(removeMessageListener);

		groupsListView = (ListView) findViewById(R.id.act_gro_lv_group_list);

	}

	private View.OnClickListener addGroupListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("GroupsActivity addGroupButton onClick", "AddGroupDialog");

			//create dialog to create new group
			AlertDialog.Builder builder = new AlertDialog.Builder(GroupsActivity.this);
			builder.setTitle("Add new group");
//			SET CUSTOM LAYOUT
			View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_group, null);
			name = (EditText) dialogView.findViewById(R.id.dialog_add_gro_et_name);
			builder.setView(dialogView);
			builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Group g = new Group();
					g.setName(String.valueOf(name.getText()));
					Log.d("Adding group to DB", "Group=" + g.toString());
					da.openToWrite();
					da.addGroup(g);
					da.close();
					updateAdapter();
				}
			});
			builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//nič
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
	};

	private View.OnClickListener deleteGroupListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("GroupsActivity deleteGroupButton onClick", "DeleteGroupDialog");
			//create dialog to delete selected groups.
			selected = groupsListViewAdapter.obtainSelected();	//pridobi izbrane skupine
			if (checkIfAtLeastOneSelected()) {
				AlertDialog.Builder builder = new AlertDialog.Builder(GroupsActivity.this);
				builder.setTitle("Confirm deletion");
				builder.setMessage("Do you really want to delete checked groups from the application?");
				builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						for (int i=0; i<selected.length; i++) {
							if (selected[i]) {
								Log.d("Deleting group from DB","Group="+groups.get(i).toString());
								da.openToWrite();
								da.deleteGroup(groups.get(i));
								da.close();
							}
						}
						updateAdapter();
					}
				});
				builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//nič
					}
				});
				builder.create();
				builder.show();
			} else {
				showAlertDialog("Error", "Check the groups you want to delete");
			}
		}
	};

	private View.OnClickListener addContactsListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			selected = groupsListViewAdapter.obtainSelected();
			if (checkIfOnlyOneGroupSelected()) {
				//prikaži AddContactsDialog
				g = returnSelectedGroup();
				requiredContacts = new ArrayList<Contact>();
				for (int i=0; i<contacts.size(); i++) {			//NAPOLNIMO POTREBNE KONTAKTE ; KRITERIJ DA NISO ŽE V TEJ SKUPINI
					if (contacts.get(i).getId_grp() != g.getId())
						requiredContacts.add(contacts.get(i));
				}
				Log.d("addContactsListener","requiredContacts.size="+requiredContacts.size());
/*android.R.style.Theme_Translucent_NoTitleBar_Fullscreen*/
				AlertDialog.Builder builder = new AlertDialog.Builder(GroupsActivity.this);
				builder.setTitle("Add contacts to group");
				View editContactsLayout = getLayoutInflater().inflate(R.layout.dialog_edit_group_contacts, null);
				editContactsListView = (ListView) editContactsLayout.findViewById(R.id.dialog_lv_contacts);
				editGroupContactsListViewAdapter = new EditGroupContactsListViewAdapter(requiredContacts, GroupsActivity.this);
				editContactsListView.setAdapter(editGroupContactsListViewAdapter);
				builder.setView(editContactsLayout);
				builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						boolean[] selected = editGroupContactsListViewAdapter.obtainSelected();
						da.openToWrite();
						for (int i=0; i<selected.length; i++) {
							if (selected[i]) {
								da.addContactInAGroup(requiredContacts.get(i), g);
							}
						}
						da.close();
						Toast.makeText(context, "Group edited, contacts successfully added", Toast.LENGTH_SHORT).show();
						updateAdapter();
					}
				});
				builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//NIČ
					}
				});
				AlertDialog aDialog = builder.create();
				DisplayMetrics dm = new DisplayMetrics();
				getWindowManager().getDefaultDisplay().getMetrics(dm);
				aDialog.getWindow().setLayout(dm.widthPixels - 50, dm.heightPixels - 50);
				aDialog.show();
			} else {
				//prikaži AlertDialog
				showAlertDialog("Error", "Check the group you want to edit!");
			}
		}
	};

	private View.OnClickListener removeContactsListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			selected = groupsListViewAdapter.obtainSelected();
			if (checkIfOnlyOneGroupSelected()) {
				//prikaži RemoveContactsDialog
				g = returnSelectedGroup();
				requiredContacts = new ArrayList<Contact>();
				for (int i=0; i<contacts.size(); i++) {			//NAPOLNIMO POTREBNE KONTAKTE ; KRITERIJ DA SO V IZBRANI SKUPINI
					if (contacts.get(i).getId_grp() == g.getId())
						requiredContacts.add(contacts.get(i));
				}
				Log.d("addContactsListener","requiredContacts.size="+requiredContacts.size());
				AlertDialog.Builder builder = new AlertDialog.Builder(GroupsActivity.this);
				builder.setTitle("Remove contacts from group");
				View editContactsLayout = getLayoutInflater().inflate(R.layout.dialog_edit_group_contacts, null);
				editContactsListView = (ListView) editContactsLayout.findViewById(R.id.dialog_lv_contacts);
				editGroupContactsListViewAdapter = new EditGroupContactsListViewAdapter(requiredContacts, GroupsActivity.this);
				editContactsListView.setAdapter(editGroupContactsListViewAdapter);
				builder.setView(editContactsLayout);
				builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						boolean[] selected = editGroupContactsListViewAdapter.obtainSelected();
						da.openToWrite();
						for (int i=0; i<selected.length; i++) {
							if (selected[i]) {
								da.removeContactFromAGroup(requiredContacts.get(i));
							}
						}
						da.close();
						Toast.makeText(context, "Group edited, contacts successfully removed", Toast.LENGTH_SHORT).show();
						updateAdapter();
					}
				});
				builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//NIČ
					}
				});
				builder.create();
				builder.show();
			} else {
				//prikaži AlertDialog
				showAlertDialog("Error", "Check the group you want to edit!");
			}
		}
	};

	private View.OnClickListener attachMessageListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("GroupsActivity deleteGroupButton onClick", "AttachMessageDialog");
			//IMPLEMENT  DIALOG Z LISTVIEWOM VSEH SPOROČIL NA VOLJO. ENAKO KOT PRI CONTACTS
			selected = groupsListViewAdapter.obtainSelected();	//pridobi izbrane skupine
			if (checkIfAtLeastOneSelected()) {
				if (messages.size() == 0) {
					showAlertDialog("Error", "Create message first");
				} else {
					ArrayList<Group> selectedGroups = new ArrayList<Group>(selected.length);
					for (int i = 0; i < groups.size(); i++) {
						if (selected[i]) {
							selectedGroups.add(groups.get(i));
						}
					}
					AttachMessageDialog amd = AttachMessageDialog.newInstance(messages, new ArrayList<Contact>(0), selectedGroups);
					amd.show(getFragmentManager(), "AttachMessageDialog GROUPS");
				}
			} else {
				//prikaži AlertDialog
				showAlertDialog("Error", "Check the groups you want to edit!");
			}
		}
	};

	private View.OnClickListener removeMessageListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("GroupsActivity deleteGroupButton onClick", "RemoveMessageDialog");
			selected = groupsListViewAdapter.obtainSelected();	//pridobi izbrane skupine
			if (checkIfAtLeastOneSelected()) {
				AlertDialog.Builder builder = new AlertDialog.Builder(GroupsActivity.this);
				builder.setTitle("Confirm message removal");
				builder.setMessage("Do you really want to delete attached message from selected groups?");
				builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						da.openToWrite();
						for (int i = 0; i < selected.length; i++) {
							if (selected[i] && (groups.get(i).getId_msg() != 0)) {
//								int id = groups.get(i).getId_msg();
								Log.d("Deleting message from selected group", "Message=KARKOLIŽE" + "Contact=" + groups.get(i).toString());
								da.removeGroupAMessage(groups.get(i));
							}
						}
						da.close();
						updateAdapter();
					}
				});
				builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//nič
					}
				});
				builder.create();
				builder.show();
			} else {
				//prikaži AlertDialog
				showAlertDialog("Error", "Check the groups you want to edit!");
			}
		}
	};

	private void updateAdapter() {
		obtainData();
		groupsListViewAdapter = new GroupsListViewAdapter(groups, messages, contacts, this);
		groupsListView.setAdapter(groupsListViewAdapter);
		context = this;
	}

	private void obtainData() {
		da.openToRead();
		groups = da.getAllGroups();
		messages = da.getAllMessages();
		contacts = da.getAllContacts();
		da.close();
	}

	private boolean checkIfOnlyOneGroupSelected() {
		int counter = 0;
		for (int i=0; i<selected.length; i++) {
			if (selected[i])
				counter++;
		}
		if (counter == 1)
			return true;
		else
			return false;
	}

	private boolean checkIfAtLeastOneSelected() {
		int counter = 0;
		for (int i=0; i<selected.length; i++) {
			if (selected[i])
				counter++;
		}
		if (counter != 0)
			return true;
		else
			return false;
	}

	private Group returnSelectedGroup() {
		for (int i=0; i<selected.length; i++) {
			if (selected[i])
				return groups.get(i);
		}
		return null;
	}

	private void showAlertDialog(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(GroupsActivity.this);
		builder.setTitle(title);
		builder.setMessage(message);
//				builder.setIcon(R.drawable.) //ALERT ICON TO BE SET
		builder.setNegativeButton(R.string.button_ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//NIČ
			}
		});
		builder.create();
		builder.show();
	}

	public void setSupportActionBarLogo() {
		getSupportActionBar().setDisplayShowHomeEnabled(true);
//		getSupportActionBar().setDisplayUseLogoEnabled(true);
//		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setIcon(R.drawable.help_app_icon);
//		getSupportActionBar().setLogo(R.drawable.help_app_icon);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_groups);
		setSupportActionBarLogo();
		setupViews();
		updateAdapter();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_groups, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch (item.getItemId()) {
			case R.id.action_contacts:
				Intent c = new Intent(this, ContactsActivity.class);
				startActivity(c);
				return true;
			case R.id.action_groups:
				Intent g = new Intent(this, GroupsActivity.class);
				startActivity(g);
				return true;
			case R.id.action_messages:
				Intent m = new Intent(this, MessagesActivity.class);
				startActivity(m);
				return true;
			case R.id.action_settings:
				Intent i = new Intent(this, SettingsActivity.class);
				startActivity(i);
				return true;
			case R.id.action_instructions:
				Intent ins = new Intent(this, InstructionsActivity.class);
				startActivity(ins);
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onConfirmAttachMessage() {
		Toast.makeText(this, "Message attached", Toast.LENGTH_SHORT).show();
		updateAdapter();
	}

	@Override
	public void onCancelAttachMessage() {
		Toast.makeText(this, "No message attached", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onConfirmEditGroup() {
		Toast.makeText(this, "Group name edited", Toast.LENGTH_SHORT).show();
		updateAdapter();
	}

	@Override
	public void onCancelEditGroup() {
		Toast.makeText(this, "Group name change cancelled", Toast.LENGTH_SHORT).show();
	}

}
